# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/4/19 17:30
# @Use :
import concurrent.futures
import datetime
import hashlib
import json
import os
import secrets
import string
import sys

import pandas as pd
import requests
from loguru import logger
from tqdm import tqdm


def log_config():
    # 添加输出处理程序，将日志输出到文件
    logger.add("./logs/info_file.log", level="INFO")
    logger.add("./logs/error_file.log", level="ERROR")


# 定义生成随机字符串的函数
def generate_random_string(length):
    alphabet = string.ascii_letters + string.digits  # 包含所有字母和数字的字符串
    return ''.join(secrets.choice(alphabet) for _ in range(length))


def send_request(flight_no, dep, arr, dep_date, cabin):
    url = 'http://121.46.237.179:10018/api/SearchAV'

    nonce = generate_random_string(32)
    timestamp = datetime.datetime.now().timestamp()
    sign = hashlib.md5(f'{nonce}44bbab23190d3fea{timestamp}'.encode()).hexdigest()

    params = {
        "context": {
            "channel": "HNYC",
            "nonce": nonce,
            "sign": sign,
            "timestamp": timestamp,
            "version": "1.0.0"
        },
        "searchCondition": {
            "segments": [{
                "arr": arr,
                "cabin": cabin,
                "chdcabin": "false",
                "code": flight_no,
                "date": dep_date,
                "dep": dep,
                "resultType": "own"
            }]
        }
    }

    response = requests.post(url, json=params)
    return json.loads(response.text)


def task_function(tf_row):
    try:
        tf_row2 = dict(tf_row)
        res_data = send_request(tf_row2.get('航班号'), tf_row2.get('起飞'), tf_row2.get('到达'),
                                tf_row2.get('出发日期'), 'R')

        # 更新进度条
        progress_bar.update(1)

        # logger.info(res_data)
        products = dict(res_data.get('Search').get('products'))
        if products.values() is not None and len(products.values()) > 0:
            product = list(products.values())[0]
            r_p_excel_df.at[tf_row.name, f'舱位'] = product['cabin'][0]['adultCabin']
            r_p_excel_df.at[tf_row.name, f'票面'] = product['adult']['printPrice']
            r_p_excel_df.at[tf_row.name, f'销售'] = product['adult']['salePrice']
            r_p_excel_df.at[tf_row.name, f'类型'] = product['adult']['policynote']
            tf_row2['舱位'] = product['cabin'][0]['adultCabin']
            tf_row2['票面'] = product['adult']['printPrice']
            tf_row2['销售'] = product['adult']['salePrice']
            tf_row2['类型'] = product['adult']['policynote']
        logger.info(tf_row2)

    except Exception as e:
        logger.error(e)


if __name__ == '__main__':
    # res_json = send_request('CZ8579', 'SZX', 'LZO', '2024-05-02', 'R')

    read_file = input("请输入读取文件名：")
    write_file = input("请输入输出文件名：")

    # 初始化日志配置
    log_config()

    # 相对文件路径
    current_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    read_path = os.path.join(current_dir, f"{read_file}.xlsx")
    write_path = os.path.join(current_dir, f"{write_file}.xlsx")

    # 读取excel文件
    r_p_excel_file = pd.ExcelFile(read_path)
    # 读取指定Sheet数据
    r_p_excel_df = r_p_excel_file.parse('Sheet1')

    total_rows = len(r_p_excel_df)
    # 创建进度条
    progress_bar = tqdm(total=total_rows, desc="执行进度", unit="次")

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for index, row in r_p_excel_df.iterrows():
            # task_function(row, account)
            executor.submit(task_function, row)

    # 关闭进度条
    progress_bar.close()

    logger.info("开始生成excel文件...")
    r_p_excel_df.to_excel(write_path, index=False)
